/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/record', 'N/search'], function (record, search) {

    function beforeLoad(context) {
        try {
            //工单发料  按钮入口  
            if (context.type === 'view') {
                var orderstatus = context.newRecord.getValue('orderstatus');
                //In Process ,D ; Released ,B
                if (orderstatus === 'B' || orderstatus === 'D') {
                    var form = context.form;
                    var url = '/app/site/hosting/scriptlet.nl?script=118&deploy=1' + '&custpage_wo_num=' + context.newRecord.id;
                    form.addButton({
                        id: 'custpage_button',
                        label: '工作单发料',
                        functionName: "window.open('" + url + "');"
                    });
                }
            }
        } catch (e) {
            log.error('beforeLoad error', JSON.stringify(e));
        }
    }

    function afterSubmit(context) {
        try {
            //设置自动生成的PO单的供应商为工单行选择的供应商
            search.create({
                type: 'purchaseorder',
                columns: [],
                filters: [['createdfrom', 'is', context.newRecord.id]]
            }).run().each(function (result) {
                var poId = result.id;
                var poRec = record.load({
                    type: 'purchaseorder',
                    id: poId,
                    isDynamic: true
                });
                var poVendorId = poRec.getValue('entity');
                var poItemId = poRec.getSublistValue('item', 'item', 0);
                var woLine = context.newRecord.findSublistLineWithValue('item', 'item', poItemId);
                var woVendorId = context.newRecord.getSublistValue('item', 'custcol_vendor', woLine);
                if (poVendorId !== woVendorId) {
                    poRec.setValue('entity', woVendorId);
                }
                poRec.save();
                return true;
            });
        } catch (e) {
            log.error('afterSubmit error', JSON.stringify(e));
        }
    }

    return {
        beforeLoad: beforeLoad,
        afterSubmit: afterSubmit
    };
});